package com.dtdream.emr;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;

/**
 * Created by moriarty on 17-8-4.
 */
@Description("_FUNC_(col) - convert column value to string")
public class GenericUDFToChar extends GenericUDF {

    private PrimitiveObjectInspector inOI;

    @Override
    public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
        if (arguments.length != 1) {
            throw new UDFArgumentException("GenericUDFToChar requires 1 argument(s), got " + arguments.length);
        }

        inOI = (PrimitiveObjectInspector) arguments[0];
        switch (inOI.getPrimitiveCategory()) {
            case BOOLEAN:
            case INT:
            case FLOAT:
                break;
            default:
                throw new UDFArgumentException("GenericUDFToChar only support boolean, integer and float");
        }

        return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    }

    @Override
    public Object evaluate(DeferredObject[] arguments) throws HiveException {
        return PrimitiveObjectInspectorUtils.getString(arguments[0].get(), inOI);
    }

    @Override
    public String getDisplayString(String[] children) {
        return getStandardDisplayString("TO_CHAR", children);
    }
}
